<?php
  
class BD extends controllerInterface{

    public $dbcnx = false;
    public $persistent;
    public $connection_established = false;
    public $insert_id = null;

    function __construct ($persistent = false){
    
        if($this->persistent === true){   
          $this->dbcnx = @mysql_pconnect(dblocation, dbuser, dbpasswd); //  [?] permanent conn
        } else {
     
          $this->dbcnx = @mysql_connect(dblocation, dbuser, dbpasswd); // non permanent conn 
          
        }
        
        if (!$this->dbcnx) $this->setError ( "BD [__construct, __FILE__, __LINE__]: error connecting db" . mysql_error() ); 
        if (!@mysql_select_db(dbname, $this->dbcnx))  $this->setError ( "BD [__construct]: error select db" . mysql_error() );
          
        if($this->dbcnx !== false){  
          $this->connection_established = true;  
          mysql_query("SET NAMES 'utf8'"); // Say to MySQl that we'll work with UTF-8   
        }  
    } // --
    
    function close(){
    
      if($this->dbcnx !== false)
        return (@mysql_close($this->dbcnx));

      return false;
    } // --

    /*
     * @return false|null|array|int
     */
    function select($sql, $is_insert = false){
    // TODO exception

        $result = null;

        $r = mysql_query($sql);
        if(!$r){
            return false;
        }

        $result = true;

        if(is_resource($r))
        if( mysql_num_rows($r) > 0){

            $result = array();

            while($row = mysql_fetch_assoc($r)){
                $result[] = $row;
            }
        }

        if($is_insert){

            $result = 0;

            $this->insert_id = mysql_insert_id();
            $result = $this->insert_id;
        }

        return $result;
    }

    function insert($sql){

        $sql = rtrim ($sql);

        $r = substr ($sql, -1);

        if($r == ';'){}
        else {
            $sql .= ';';
        }

        ///$sql .= "SELECT LAST_INSERT_ID();";

        //$this->pk = last_insert_id();//



        return $this->select($sql, $is_insert = true);
    }

    function update($sql){
        $sql = rtrim ($sql);

        $r = substr ($sql, -1);

        if($r == ';'){}
        else {
            $sql .= ';';
        }

        return $this->select($sql, $is_insert = false);
    }


    function query($sql){
        return $this->select($sql);
    }

}
  
  
  
?>